package com.langChain4j.agent;

import com.langChain4j.agent.impl.OrderAgent;
import com.langChain4j.agent.impl.SalesAgent;
import com.langChain4j.agent.impl.SupportAgent;
import com.langChain4j.api.constants.ModelHostConstant;
import com.langChain4j.api.enums.ModelEnum;
import dev.langchain4j.model.ollama.OllamaChatModel;
import dev.langchain4j.service.AiServices;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 智能体协调器 - 负责调度和协调多个智能体协作
 */
@Slf4j
@Component
public class AgentCoordinator {

    private List<Agent> agents;

    private CoordinatorService coordinatorService;

    @PostConstruct
    public void init() {
        // 创建协调器使用的AI模型
        OllamaChatModel chatModel = OllamaChatModel.builder()
                .baseUrl(ModelHostConstant.OLLAMA_API_URL)
                .modelName(ModelEnum.MODEL_OLLAMA_DEFAULT.getCode())
                .temperature(1.0)
                .build();
        // 创建各个智能体
        Agent productAgent = AiServices.builder(OrderAgent.class).chatModel(chatModel).build();
        Agent orderAgent = AiServices.builder(SalesAgent.class).chatModel(chatModel).build();
        Agent techAgent = AiServices.create(SupportAgent.class, chatModel);
        this.agents = Arrays.asList(productAgent, orderAgent, techAgent);
        // 创建协调器服务
        this.coordinatorService = AiServices.builder(CoordinatorService.class).chatModel(chatModel).build();
    }

    /**
     * 处理用户查询，协调智能体协作
     */
    public String processQuery(String query) {
        // 1. 生成智能体信息描述
        StringBuilder agentInfo = new StringBuilder();
        agentInfo.append("可用智能体列表：\n");
        for (Agent agent : agents) {
            agentInfo.append("- 名称：").append(agent.getName())
                    .append("，描述：").append(agent.getDescription()).append("\n");
        }
        log.info("智能体信息：{}", agentInfo.toString());
        // 2. 让协调器决定处理方案
        String coordinationPlan = coordinatorService.planCoordination(query, agentInfo.toString());
        
        // 3. 执行协调方案
        if (coordinationPlan.contains("需要多个智能体协作")) {
            return handleCollaboration(query);
        } else {
            // 找到最合适的单个智能体处理
            for (Agent agent : agents) {
                if (coordinationPlan.contains(agent.getName()) || agent.canHandle(query)) {
                    return agent.handle(query);
                }
            }
        }
        
        // 4. 如果没有合适的智能体，返回默认回复
        return "抱歉，我暂时无法处理您的问题。请尝试其他表述或联系人工客服。";
    }

    /**
     * 处理多智能体协作场景
     */
    private String handleCollaboration(String query) {
        StringBuilder result = new StringBuilder("您的问题需要多个部门协作处理：\n");
        
        // 收集所有能处理该查询的智能体的回复
        for (Agent agent : agents) {
            if (agent.canHandle(query)) {
                result.append("\n")
                      .append(agent.getName()).append("的回复：\n")
                      .append(agent.handle(query)).append("\n");
            }
        }
        
        result.append("\n以上是相关部门的回复汇总，希望能解决您的问题。");
        return result.toString();
    }

}
    